<?php
/**
 * 接口用户模型
 * @author sundongdong
 * @date 2016-07-12
 */
class Application_Model_User extends Model_Base {
	/**
	 * 批量添加用户
	 * @param unknown $data
	 */
	public function addUsers($data) {
		try {
			$this->db('write_db')->beginTransaction();
			$this->insertBatch($this->db('write_db'),'s_user', $data);
			$this->db('write_db')->commit();	
		} catch (Exception $e) {
			$this->db('write_db')->rollBack();
			throw $e;
		}
	}
	/**
	 * 添加用户
	 * @param array $data
	 */
	public function add(array $data) {
		try {
			$this->db('write_db')->insert('s_user', $data);
		} catch (Exception $e) {
			return array('opr' => 0, 'content' => $e->getMessage());
		}
	}
	/**
	 * 用户是否存在检查
	 * @param string $username
	 */
	public function exist($username = '') {
		return $this->db()->fetchOne("select user_id from s_user where user_name = :user_name", array('user_name' => $username));
	}
	/**
	 * 更新用户信息
	 * @param array $data
	 * @param number $user_id
	 */
	public function update(array $data, $user_id = 0) {
		try {
			$where = $this->db('write_db')->quote('user_id=?', $user_id);
			$this->db('write_db')->update('s_user', $data, $where);
		} catch (Exception $e) {
			return array('opr' => 0, 'content' => $e->getMessage());
		}
	}
	/**
	 * 删除用户
	 * @param string $username
	 */
	public function delete($username = '') {
		try {
			$where = $this->db('write_db')->quote('user_name=?', $username);
			$this->db('write_db')->update('s_user', array('is_enable' => 0), 'user_name=' . $where);
			return array('opr' => 1, 'content' => '删除成功');
		} catch (Exception $e) {
			return array('opr' => 0, 'content' => $e->getMessage());
		}
	}
	/**
	 * 获取当前登录用户的分类权限
	 */
	public static function getCategory() {
		$user_id = Model_User::currentLoginUser()->user_id;
		if (!$user_id) {
			return array();
		}
		$db = Model_Db::getInstance();
		$result = $db->fetchPairs("select id,category_id from s_user_category where user_id=:uid", ['uid' => $user_id]);
		if (!array_values($result)) {
			return [0];
		}
		return array_values($result);
	}
	/**
	 * 获取当前登录用户的仓库权限
	 */
	public static function getWarehouse() {
		$user_id = Model_User::currentLoginUser()->user_id;
		if (!$user_id) {
			return array();
		}
		$db = Model_Db::getInstance();
		$result = $db->fetchCol("select warehouse.warehouse_code from s_user_warehouse as user_warehouse left join c_warehouse as warehouse on user_warehouse.warehouse_id=warehouse.id where user_id=:uid and warehouse_id>0", ['uid' => $user_id]);
		if (!array_values($result)) {
			return [''];
		}
		return array_values($result);
	}
}